package com.example.demo.controller;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.controller.dto.user.AddUserDto;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.util.R;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@RestController()
@RequestMapping("/user")
@Api(value = "用户接口", tags = { "用户接口" })
public class UserController {

  @Autowired
  private UserService userService;

  @PostMapping(value = "/add")
  @ApiOperation(value = "添加用户", code = 200, httpMethod = "POST")
  @ApiResponses({
      @ApiResponse(code = 200, message = "添加成功"),
  })
  public R addUser(@RequestBody AddUserDto userDto) {
    User _user = userService.findByName(userDto.getName());

    if (_user != null) {
      return R.fail("用户名已存在");
    }

    User user = new User(userDto.getName(), userDto.getPassword(), new Date());

    boolean flag = userService.add(user);

    if (flag) {
      return R.success("添加成功");
    } else {
      return R.fail("添加失败");
    }
  }

  @PostMapping(value = "/update")
  public R updateUser(@RequestBody User body) {
    User user = userService.findOne(body.getId());
    user.setName(body.getName());
    user.setPassword(body.getPassword());
    user.setUpdate_time(new Date());

    boolean flag = userService.update(user);

    if (flag) {
      return R.success("更新成功");
    } else {
      return R.fail("更新失败");
    }
  }

  @ApiOperation(value = "查找用户", code = 200, httpMethod = "GET")
  @GetMapping("/find")
  public R findUsers(@ApiParam(name = "query", value = "参数") @RequestParam Map<String, String> query) {
    User[] users = userService.find(query.get("name"));

    return R.success(users);
  }

  @PostMapping("/delete")
  public R deleteUser(@RequestBody Map<String, String> body) {
    if (body.get("id") == null) {
      return R.fail("参数不合法");
    }

    int result = userService.delete(Integer.parseInt(body.get("id")));
    if (result > 0) {
      return R.success();
    } else {
      return R.fail();
    }
  }

}
